<template>
  <div class="container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
      <p>正在加载酒店信息...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <a-result
        status="error"
        title="加载失败"
        :sub-title="errorMessage"
      >
        <template #extra>
          <a-button type="primary" @click="loadDetail">重新加载</a-button>
          <a-button @click="$router.push('/')">返回首页</a-button>
        </template>
      </a-result>
    </div>
    
    <!-- 酒店详情 -->
    <div v-else-if="hotel">
      <div class="banner">
        <div class="back">
          <a-button size="small" @click="$router.push('/')">返回首页</a-button>
        </div>
        <img class="cover" :src="hotel.imageUrl || fallbackImg(hotel.id)" alt="hotel" />
        <div class="title">
          <h2>{{ hotel.name }}</h2>
          <div class="sub">⭐ {{ hotel.star }} · {{ hotel.address }} · 客服：<a :href="`tel:${hotel.tel}`">{{ hotel.tel || '—' }}</a></div>
        </div>
      </div>

      <div class="intro">{{ hotel.description }}</div>

      <h3>房型与价格</h3>
      <div class="rooms">
        <div v-if="rooms.length === 0" class="no-rooms">
          <a-empty description="暂无房间信息" />
        </div>
        <div class="room" v-for="r in rooms" :key="r.id">
          <div class="room-image">
            <img :src="r.imageUrl || fallbackRoomImg(r.id)" :alt="r.roomType" />
          </div>
          <div class="room-info">
            <div class="name">{{ r.roomType }}</div>
            <div class="description" v-if="r.description">{{ r.description }}</div>
            <div class="price">￥{{ r.price }}</div>
            <div class="inv">库存：{{ r.inventory }}</div>
            <a-button type="primary" size="small" @click="selectRoom(r)">预订</a-button>
          </div>
        </div>
      </div>

      <a-modal v-model:open="orderVisible" title="预订房间" :footer="null">
        <a-form layout="vertical" @submit.prevent>
          <a-form-item label="姓名">
            <a-input v-model:value="orderForm.realName" placeholder="请输入姓名" />
          </a-form-item>
          <a-form-item label="电话">
            <a-input v-model:value="orderForm.tel" placeholder="请输入手机号" />
          </a-form-item>
          <a-form-item label="身份证号码">
            <a-input v-model:value="orderForm.idCard" placeholder="请输入身份证号码" />
          </a-form-item>
          <a-form-item label="入住/离店日期">
            <a-range-picker v-model:value="orderForm.dateRange" @change="onDateChange" />
            <div v-if="previewPrice>0" style="margin-top:8px;color:#888;">预估单晚价格：￥{{ previewPrice }}</div>
          </a-form-item>
          <a-form-item label="支付方式">
            <a-radio-group v-model:value="orderForm.paymentMethod" style="display: flex; gap: 24px;">
              <a-radio value="alipay" style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border: 2px solid #f0f0f0; border-radius: 8px; transition: all 0.3s;">
                <div style="width: 24px; height: 24px; background: linear-gradient(135deg, #1677ff, #4096ff); border-radius: 4px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">支</div>
                <span style="font-weight: 500;">支付宝</span>
              </a-radio>
              <a-radio value="wechat" style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border: 2px solid #f0f0f0; border-radius: 8px; transition: all 0.3s;">
                <div style="width: 24px; height: 24px; background: linear-gradient(135deg, #07c160, #38d865); border-radius: 4px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">微</div>
                <span style="font-weight: 500;">微信支付</span>
              </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
              <div style="font-size: 18px; font-weight: 600; color: #e53935;">
                总价：￥{{ calculateTotalPrice() }}
              </div>
            </div>
            <a-space>
              <a-button @click="orderVisible=false">取消</a-button>
              <a-button type="primary" :loading="submitting" @click="submitOrder">提交并支付</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-modal>

      <h3>用户评价 <span v-if="avgRating>0" style="font-size:14px;color:#faad14;">（平均分：{{ avgRating.toFixed(1) }}）</span></h3>
      <div class="reviews">
        <div class="review" v-for="rv in reviews" :key="rv.id">
          <div class="rating">评分：{{ rv.rating }} / 5</div>
          <div class="content">{{ rv.content }}</div>
        </div>
        <div v-if="!reviews || reviews.length===0" class="empty">暂无评价</div>
        <div class="review-form">
          <a-rate v-model:value="newReview.rating" :count="5" />
          <a-input-textarea v-model:value="newReview.content" :rows="3" placeholder="写下你的入住体验..." style="margin:8px 0" />
          <a-button type="primary" size="small" :loading="submittingReview" @click="submitReview">提交评价</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { hotelAPI } from '@/api/hotel'
import { roomAPI } from '@/api/room'
import { orderAPI } from '@/api/order'
import { paymentAPI } from '@/api/payment'
import request from '@/utils/request'
import dayjs from 'dayjs'

const route = useRoute()
const hotelId = Number(route.params.id)
const hotel = ref(null)
const rooms = ref([])
const reviews = ref([])
const avgRating = ref(0)
const newReview = ref({ rating: 5, content: '' })
const submittingReview = ref(false)

const loading = ref(false)
const error = ref(false)
const errorMessage = ref('')

const orderVisible = ref(false)
const submitting = ref(false)
const selectedRoom = ref(null)
const orderForm = ref({ realName: '', tel: '', idCard: '', dateRange: [], paymentMethod: 'alipay' })
const previewPrice = ref(0)

const loadDetail = async () => {
  loading.value = true
  error.value = false
  errorMessage.value = ''
  
  try {
    const [hres, rres, rvres] = await Promise.all([
      hotelAPI.detail(hotelId),
      roomAPI.list(hotelId, 1, 50),
      request.get('/po/reviews', { params: { hotelId } })
    ])
    
    hotel.value = hres.data?.data || hres.data || null
    
    // 处理房间数据
    const roomList = rres.data?.data?.list || rres.data?.list || rres.data || []
    rooms.value = roomList.map(x => ({
      id: x.id,
      roomType: x.roomType || x.room_type,
      price: x.price,
      inventory: x.inventory,
      imageUrl: x.imageUrl || x.image_url,
      description: x.description
    }))
    
    const rvPayload = rvres.data?.data || rvres.data || {}
    const rvList = Array.isArray(rvPayload) ? rvPayload : (rvPayload.list || [])
    reviews.value = rvList
    // 计算平均分
    if (rvList.length > 0) {
      const sum = rvList.reduce((acc, it) => acc + (Number(it.rating) || 0), 0)
      avgRating.value = sum / rvList.length
    } else {
      avgRating.value = 0
    }
    
    if (!hotel.value) {
      throw new Error('酒店信息不存在')
    }
  } catch (err) {
    console.error('加载酒店详情失败:', err)
    error.value = true
    
    if (err.response?.status === 404) {
      errorMessage.value = '酒店不存在，请检查酒店ID是否正确'
    } else if (err.code === 'ECONNREFUSED' || err.message.includes('Network Error')) {
      errorMessage.value = '无法连接到服务器，请确保后端服务已启动'
    } else if (err.message === '酒店信息不存在') {
      errorMessage.value = '酒店信息不存在'
    } else {
      errorMessage.value = err.response?.data?.message || err.message || '加载酒店详情失败'
    }
  } finally {
    loading.value = false
  }
}
const submitReview = async () => {
  if (!newReview.value.rating) {
    alert('请给出评分')
    return
  }
  if (!newReview.value.content || newReview.value.content.trim().length < 3) {
    alert('请至少填写3个字的评价内容')
    return
  }
  submittingReview.value = true
  try {
    await request.post('/po/reviews', { hotelId, rating: newReview.value.rating, content: newReview.value.content })
    newReview.value = { rating: 5, content: '' }
    await loadDetail()
  } catch (e) {
    console.error('提交评价失败', e)
  } finally {
    submittingReview.value = false
  }
}

onMounted(() => {
  loadDetail()
})

const fallbackImg = (id) => {
  return `https://picsum.photos/400/260?random=${id}`
}

const fallbackRoomImg = (id) => {
  return `https://picsum.photos/300/200?random=room${id}`
}

const selectRoom = (room) => {
  selectedRoom.value = room
  orderVisible.value = true
  orderForm.value = { realName: '', tel: '', idCard: '', dateRange: [], paymentMethod: 'alipay' }
  previewPrice.value = 0
}

const onDateChange = async () => {
  if (!selectedRoom.value || !orderForm.value.dateRange || orderForm.value.dateRange.length < 2) {
    previewPrice.value = 0
    return
  }
  
  try {
    const checkIn = dayjs(orderForm.value.dateRange[0]).format('YYYY-MM-DD')
    const res = await roomAPI.priceOn(selectedRoom.value.id, checkIn)
    const payload = res.data?.data || res.data || {}
    previewPrice.value = payload.price || 0
  } catch (error) {
    // 忽略价格查询错误，保持预览价格为0
    console.debug('价格查询失败:', error)
  }
}

const calculateTotalPrice = () => {
  if (!orderForm.value.dateRange || orderForm.value.dateRange.length < 2 || previewPrice.value <= 0) {
    return 0
  }
  
  const checkIn = dayjs(orderForm.value.dateRange[0])
  const checkOut = dayjs(orderForm.value.dateRange[1])
  const nights = checkOut.diff(checkIn, 'day')
  
  return (previewPrice.value * nights).toFixed(2)
}

const submitOrder = async () => {
  if (!orderForm.value.realName || !orderForm.value.tel || !orderForm.value.idCard || !orderForm.value.dateRange || orderForm.value.dateRange.length < 2) {
    return
  }
  
  submitting.value = true
  try {
    const checkIn = dayjs(orderForm.value.dateRange[0]).format('YYYY-MM-DD')
    const checkOut = dayjs(orderForm.value.dateRange[1]).format('YYYY-MM-DD')
    const totalPrice = calculateTotalPrice()
    
    const orderData = {
      userId: JSON.parse(localStorage.getItem('userInfo') || '{}').id,
      hotelId: hotelId,
      roomId: selectedRoom.value.id,
      checkinDate: checkIn,
      checkoutDate: checkOut
    }
    
    const orderRes = await orderAPI.create(orderData)
    const orderId = orderRes.data?.data || orderRes.data
    
    const paymentData = {
      orderId: orderId,
      amount: parseFloat(totalPrice),
      paymentMethod: orderForm.value.paymentMethod
    }
    
    const paymentRes = await paymentAPI.create(paymentData)
    const paymentResult = paymentRes.data?.data || paymentRes.data
    
    if (paymentResult?.status === 'SUCCESS') {
      alert('支付成功！订单ID: ' + orderId + '，支付ID: ' + paymentResult.paymentId)
      // 可以选择跳转到订单页面
      // router.push('/fouter/orders')
    } else {
      alert('支付失败: ' + (paymentResult?.message || '未知错误'))
    }
    
    orderVisible.value = false
  } catch (error) {
    console.error('提交订单失败:', error)
    alert('提交订单失败: ' + (error.response?.data?.message || error.message))
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.container { padding-bottom: 24px; }

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
}

.loading-container p {
  margin-top: 16px;
  color: #666;
  font-size: 16px;
}

.error-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner { position: relative; }
.cover { width: 100%; height: 260px; object-fit: cover; display: block; }
.back { position: absolute; left: 16px; top: 12px; z-index: 2; }
.title { position: absolute; left: 16px; bottom: 10px; color: #fff; text-shadow: 0 2px 10px rgba(0,0,0,.5); }
.intro { padding: 12px 16px; color: #333; }
.rooms { padding: 0 16px 16px; display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; }
.room { border: 1px solid #eee; border-radius: 8px; overflow: hidden; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.room-image { width: 100%; height: 160px; overflow: hidden; }
.room-image img { width: 100%; height: 100%; object-fit: cover; }
.room-info { padding: 12px; display: flex; flex-direction: column; gap: 8px; }
.name { font-size: 16px; font-weight: 600; color: #333; }
.description { font-size: 12px; color: #666; line-height: 1.4; }
.price { color: #e53935; font-weight: 600; font-size: 18px; }
.inv { font-size: 12px; color: #999; }
.no-rooms { 
  grid-column: 1 / -1; 
  display: flex; 
  justify-content: center; 
  align-items: center; 
  min-height: 120px; 
}
.reviews { padding: 0 16px; display: grid; gap: 12px; }
.review { border: 1px solid #f0f0f0; border-radius: 6px; padding: 10px; }
.empty { color: #888; font-size: 13px; padding: 8px 0; }

/* 支付方式样式 */
:deep(.ant-radio-wrapper-checked) {
  border-color: #1677ff !important;
  background-color: #f6f8ff !important;
}

:deep(.ant-radio-wrapper-checked[value="wechat"]) {
  border-color: #07c160 !important;
  background-color: #f6fff6 !important;
}
</style>